package org.dxy.service.impl;

import org.dxy.entity.User;
import org.dxy.mapper.UserMapper;
import org.dxy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

// 用户服务实现类
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User register(User user) {
        // 对密码进行加密等处理后保存用户信息
        return userMapper.save(user);
    }

    @Override
    public User login(String usernameOrPhone, String password) {
        User user = userMapper.findByUsername(usernameOrPhone);
        if (user == null) {
            user = userMapper.findByPhone(usernameOrPhone);
        }
        if (user!= null && passwordEncoder.matches(password, user.getPassword())) {
            return user;
        } else {
            return null;
        }
    }

    @Override
    public User updateUser(User user) {
        // 更新用户信息并保存
        return userMapper.save(user);
    }

    @Override
    public void resetPassword(String phone, String newPassword) {
        User user = userMapper.findByPhone(phone);
        if (user!= null) {
            user.setPassword(passwordEncoder.encode(newPassword));
            userMapper.save(user);
        }
    }
}
